﻿
using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Utility;
using YouHP.BLL;
using YouHP.Model;

namespace YouHP.Pages.IndicatorHistory
{
    public class IndicatorAjax : YouHP.Pages.BasePage
    {

        protected override void ShowPage()
        {
            base.ShowPage();
            if (ErrorCount > 0) return;

            if (IsPost == false) HandleGet();
        }

        protected void HandleGet()
        {
            int idcid = RequestTools.GetQueryInt("idcid", 0);
            if (idcid <= 0)
            {
                return;
            }

            LabcheckInfo indicatorData = LabcheckBLL.Instance.GetLabcheckInfo(idcid);
            if (indicatorData.Id <= 0)
            {
                return;
            }

            if (UserData.Id <= 0) return;
            PatientRecordInfo prData = PatientBLL.Instance.GetPatientRecordInfo(UserData.Id);
            if (prData.Id <= 0) return;

            List<IndicatorHistoryInfo> lst = PatientIndicatorBLL.Instance.GetIndicatorHistoryList(prData.Id, idcid);

            MakeGraphData(prData, indicatorData, lst);
        }

        private void MakeGraphData(PatientRecordInfo prData, LabcheckInfo indicatorData, List<IndicatorHistoryInfo> lst)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("&SingleIndicator=1&\r\n");
            sb.AppendFormat("&StartDate={0:yyyy-MM-dd}&\r\n", prData.StartDate);
            sb.AppendFormat("&DosageDate={0:yyyy-MM-dd}&\r\n", prData.ConfirmDate);
            sb.AppendFormat("&UpdateDate={0:yyyy-MM-dd}&\r\n", prData.UpdateDate);

            sb.AppendFormat("&Axis={0}&\r\n", indicatorData.GridValues.Trim());

            //对于单位"%"需要特殊处理(转换成"#")
            if (indicatorData.MeasurementUnits.Equals("%"))
            {
                indicatorData.MeasurementUnits = "#";
            }
            sb.AppendFormat("&Var=Indicator;{0};{1};{2}&\r\n", indicatorData.MeasurementUnits, 
                indicatorData.IsQuantified > 0 ? 1:0, lst.Count);

            int cnt = lst.Count - 1;
            for (int i = 0; i <= cnt; i++)
            {
                IndicatorHistoryInfo info = lst[cnt - i];
                sb.AppendFormat("&Data_{0}={1:yyyy-MM-dd};{2}&\r\n",
                    i,
                    info.RecordDate,
                    info.DataValue
                    );
            }

            ResponseXML(sb);
        }

        private void ResponseXML(StringBuilder sb)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "Text/html";
            System.Web.HttpContext.Current.Response.Expires = 0;

            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
    }
}